<script>
  import store from '@/store'
  import StoreModel from '@/common/model/Store'
  import { getSceneData } from './core/app'
  import { isObject } from './utils/util'
  import weixinSdk from 'weixin-js-sdk'
  import * as UserApi from '@/api/user'
  export default {

    /**
     * 全局变量
     */
    globalData: {},
	
    /**
     * 初始化完成时触发
     */
    onLaunch({ path, query, scene }) {
	  //判断是不是微信环境
	  this.isWxMiniCodeWebviewEnv()
      // #ifdef MP
      // 小程序主动更新
      this.updateManager()
      // #endif
      // app启动参数
      this.onStartupQuery(isObject(query) ? query : {})
      // 获取商城基础信息
      this.getStoreInfo()
    },

    methods: {
	  isWxMiniCodeWebviewEnv() {
		const app = this
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
		  //ios的ua中无miniProgram，但都有MicroMessenger（表示是微信浏览器）
		  weixinSdk.miniProgram.getEnv((res) => {
			if (res.miniprogram) {
			  //小程序环境
			 //  weixinSdk.miniProgram.switchTab({
				// url: "/pages/personal/index",
				// });
			} else {
			  // 微信环境非小程序
			  console.log('微信浏览器打开，非小程序')
			}
		  });
		} else {
		  // 其他浏览器
		  console.log("不在微信里");
		  uni.showModal({
		    title: '温馨提示',
		    content: '需要在微信中打开',
		    // showCancel: false,
		    confirmText: "复制并打开",
		    cancelText: "取消",
		    success: res => {
		      if (res.confirm) {
				  console.log('res.confirm',res.confirm)
		       // weixinSdk.miniProgram.navigateTo({
		       //   url:'http://wly.xcnf.com//index.php?s=/api/wechat/getAuthUrl&refereeId='+ uni.getStorageSync('userId')
		       // })
			   const url = 'http://wly.xcnf.com//index.php?s=/api/wechat/getAuthUrl&refereeId='+ uni.getStorageSync('userId')
			   const redirectUriWithId = encodeURIComponent(`http://wly.xcnf.com/h5/#/pages/login/index?refereeId=${uni.getStorageSync('userId')}`);
			   let state = 'stateFlag'; 
			   const authUrl =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3b47847daab70b92&redirect_uri=${redirectUriWithId}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
			   // 复制到剪贴板
			    uni.setClipboardData({
			      data: url,
			      success: () => {
					  app.$toast('链接复制成功，快去发送给朋友吧~')
					  // window.location.href = `weixin://biz/ww/profile/${encodeURIComponent(url)}`
					   // window.location.href = `weixin://dl/business/?ticket=${url}`
					   // window.location.href = 'weixin://dl/scan' // 微信扫一扫
					    // window.location.href = authUrl
					   window.location.href = `weixin://` //dl/businessWebview/link/?appid=wx3b47847daab70b92&url=${encodeURIComponent(url)}
					   // let ifr = document.createElement("iframe");
					   // ifr.src = `weixin://dl/business/?appid=wx3b47847daab70b92&url=${encodeURIComponent(url)}`;
					   // ifr.style.display = "none";
					   // document.body.appendChild(ifr)
					   // 调用方法
					   // app.openWechatLink(url);
				  },
			      fail: ({ errMsg }) => app.$toast('复制失败 ' + errMsg),
			      complete: () => {
			   	  }
			    })
		      }
		      if (res.cancel && getCurrentPages().length > 1) {
		        uni.navigateBack()
		      }
		    }
		  })
		}	 
	  },
	  //外部浏览器调起微信打开指定链接
	  openWechatLink(url) {
	    if(typeof WeixinJSBridge == "undefined") {
	      if(document.addEventListener) {
	        document.addEventListener('WeixinJSBridgeReady', function() {
	          this.openLink(url);
	        }, false);
	      } else if(document.attachEvent) {
	        document.attachEvent('WeixinJSBridgeReady', function() {
	          this.openLink(url);
	        });
	        document.attachEvent('onWeixinJSBridgeReady', function() {
	          this.openLink(url);
	        });
	      }
	    } else {
	      this.openLink(url);
	    }
	  },
	  openLink(url) {
	    WeixinJSBridge.invoke('openUrl', {
	      "url": url,
	      "delay": 0
	    });
	  },
      // app启动参数
      onStartupQuery(query) {
        // 获取二维码场景值
        // const scene = getSceneData(query)
      },

      // 获取商城基础信息
      getStoreInfo() {
        StoreModel.data(false)
      },

      // 小程序主动更新
      updateManager() {
        const updateManager = uni.getUpdateManager()
        updateManager.onCheckForUpdate(res => {
          // 请求完新版本信息的回调
          // console.log(res.hasUpdate)
        })
        updateManager.onUpdateReady(() => {
          uni.showModal({
            title: '更新提示',
            content: '新版本已经准备好，即将重启应用',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
        updateManager.onUpdateFailed(() => {
          // 新的版本下载失败
          uni.showModal({
            title: '更新提示',
            content: '新版本下载失败',
            showCancel: false
          })
        })
      }

    }

  }
</script>

<style lang="scss">
  /* uView库样式 */
  @import "./uni_modules/vk-uview-ui/index.scss";
  /* 项目基础样式 */
  @import "./app.scss";
  /* iconfont图标库 */
  @import "./utils/iconfont.scss";
</style>